﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.App.Apilication.Common.Deep;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure.Interfance;

namespace Traceability.App.Apilication.Handler.Deep
{
    public class CreateDeepHandler : IRequestHandler<CreateDeepCommon, ApiResult<int>>
    {
        private readonly IBaseRespository<DeepProcessing> deepProcessingRepo;
        private readonly IMapper mapper;

        public CreateDeepHandler(IBaseRespository<DeepProcessing> DeepProcessingRepo,IMapper mapper)
        {
            deepProcessingRepo = DeepProcessingRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateDeepCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            var model = mapper.Map<DeepProcessing>(request);
            model.CreateTime = DateTime.Now;
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = deepProcessingRepo.Add(model).Result;
                tran.Complete();
            }

            if (r > 0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "添加成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "添加失败";
                return Task.FromResult(res);
            }
        }
    }
}
